package com.gientech.service.impl;

import com.alibaba.fastjson.JSON;
import com.gientech.entity.LoanInfo;
import com.gientech.entity.UserInfo;
import com.gientech.mapper.LoanInfoMapper;
import com.gientech.service.LoanInfoService;
import com.gientech.utils.UserInfoContextHolder;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;

@Service
public class LoanInfoServiceImpl implements LoanInfoService {

    @Autowired
    private LoanInfoMapper loanInfoMapper;
    @Autowired
    private ProcessEngine processEngine;

    @Override
    public void insertLoanInfo(LoanInfo loanInfo) {
        loanInfoMapper.insertSelective(loanInfo);
    }

    @Override
    public List<LoanInfo> queryTaskByUserName(String useName) {
        return loanInfoMapper.queryTaskByUserName(useName);
    }

    @Override
    public String startTask() {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance process = runtimeService.startProcessInstanceByKey("loan");
        // 获取流程实例id
        return process.getProcessInstanceId();
    }

    @Override
    public void checkApply(LoanInfo loanInfo) {
        // 获取当前登录人信息
        UserInfo userInfo = UserInfoContextHolder.getUserInfo();
        String currentUserName = userInfo.getUsername();
        // 完成当前登录人任务
        TaskService taskService = processEngine.getTaskService();
        TaskQuery taskQuery = taskService.createTaskQuery().processDefinitionKey("loan");
        List<Task> taskList = taskQuery.taskAssignee(currentUserName).processInstanceId(loanInfo.getTaskId()).list();

        HashMap<String, Object> map = new HashMap<>();
        map.put("approve", loanInfo.getApprove());
        for(Task task: taskList){
            taskService.complete(task.getId(), map);
        }

        // 更新贷款审批流程信息
        loanInfoMapper.updateByPrimaryKeySelective(loanInfo);

        // A02为贷款主管账号， 将如果贷款主管审核通过贷款后，将贷款信息发送给风控部门
        boolean isSendToRisk = "A02".equals(currentUserName) && "1".equals(loanInfo.getApprove());
        if(isSendToRisk){
            try {
                //sendLoanInfoToRisk(loanInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void sendLoanInfoToRisk(LoanInfo loanInfo) throws Exception {
// 实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("provider");
        // 设置NameServer的地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        //启动Producer实例
        producer.start();
        // 将需要传递的对象转成json
        String loanInfoJson = JSON.toJSONString(loanInfo);
        System.out.println("将需要传递的对象转成json>>>>" + loanInfoJson);
        Message msg = new Message("LoanTopic", "Tag", loanInfoJson.getBytes(StandardCharsets.UTF_8));
        //发送消息到一个Broker
        SendResult sentResult = producer.send(msg);
        //通过sentResult返回消息是否成功发送
        System.out.printf("%s%n", sentResult);
        //如果不再发送消息，关闭Producer实例
        producer.shutdown();
    }
}
